//index.js
//获取应用实例

var app = getApp()
var requests = require('../../requests/api.js');
Page({

  //数据初始化
  data: {
    //没有更多
    loading: true,        //加载框是否显示
    searchLoading: false,  //把"上拉加载"的变量设为true，显示  
    searchLoadingComplete: false, //把“没有数据”设为false，隐藏  
    page: 1,                  //分页数据，从第一页开始
    allSelect: false,       //全部领取按钮
    color: "",
    slideAnimation: {},
    maskDisplay: 'none',
    moduleData: [],
    goods: [
    ],
    couponArray: [
    ]
  },
  //MARK: -- system method
  onLoad: function () {
    new app.WeToast();
    this.setData({
      page: 1,              //分页从第一页开始加载
      goods: [],             //初始化商品数组
      searchLoading: true,  //把"上拉加载"的变量设为true，显示  
      searchLoadingComplete: false //把“没有数据”设为false，隐藏  
    });
    this.request_indexData(this.data.page);      //加载产品列表数据
    this.request_banner();                 //加载banner数据
  },

  /**
   * 当页面滑动到底部时触发的方法,删掉这个方法后控制台会报事件警告
   */
  onReachBottom: function () {
  },

  getUserInfo() {
    var that = this
    //调用应用实例的方法获取全局数据
    app.login({
      //success回调
      success: function (endUser) {
        //更新数据
        that.slideOpen();

      },
      fail: null,
      authFail: () => { },
    })
  },
  //NET 
  request_indexData: function (page) {
    //网络请求的时候先把加载框加出来
    const self = this;
    self.setData({
      loading: false,
    });
    var params = {
      currentPage: page,
      pageSize: 10
    };

    requests.get_productData(params, (res) => {
      if (!res.data.products) return;
      if (res.data.products.length == 0) {    //没有数据
        self.setData({
          searchLoadingComplete: true, //把“没有数据”设为true，显示

        })
      } else {      //说明还有数据
        self.setData({
          searchLoadingComplete: false,//把“没有数据”设为false，隐藏  

        })
      };
      self.setData({
        loading: true,      //隐藏加载框
        goods: self.data.goods.concat(res.data.products)    //给数组赋值
      })

    }, () => {
      self.setData({
        searchLoadingComplete: true, //把“没有数据”设为true，显示
        loading: true      //隐藏加载框
      })

    }, () => {
      self.setData({
        searchLoading: false   //把"上拉加载"的变量设为false，隐藏  

      })
    });
  },

  request_banner: function () {
    const self = this
    var params = {
    };

    requests.get_bannerData(params, (res) => {
      self.setData({
        //bannerLinkType 6商品详情 8专题
        moduleData: res.data.modules,
      })
    }, () => {
    }, () => {
    });
  },

  //用户可领取优惠券
  request_coupons: function () {
    const that = this
    var params = {
    };
    requests.get_recommendCoupons(params, (res) => {
      that.setData({
        //优惠券数组
        couponArray: res.data,
      })
      that.allSelect()
    }, () => {
    }, () => {
    });
  },

  //用户领券
  request_postCoupons: function (index) { 
    const that = this
    var couponsArr = that.data.couponArray
    let couponId = couponsArr[index].id
    var hasReceived = couponsArr[index].hasReceived
    if (hasReceived) {
      return
    }
    wx.showLoading({
      title: '',
    });
    var params = {
      ids: [couponId]
    };
    requests.post_coupons(params, (res) => {
      that.wetoast.toast({
        title: '领取成功',
      })
      couponsArr[index].hasReceived = true
      that.setData({
        couponArray: couponsArr,
      })
      that.allSelect()

    }, () => {
    }, () => {
    });
  },

  //用户领券
  request_allCoupons: function (ids) {
    wx.showLoading({
      title: '',
    });
    const that = this
    var params = {
      ids: ids
    };
    var couponsArr = that.data.couponArray

    requests.post_coupons(params, (res) => {
      that.wetoast.toast({
        title: '领取成功',
      })
      for (var i = 0; i < couponsArr.length; i++) {
        var curItem = couponsArr[i];
        curItem.hasReceived = true;
      }
      this.setData({
        couponArray: couponsArr,
        allSelect: true
      })
    }, () => {
    }, () => {
    });
  },

  //上拉触底
  moreData: function () {
    let that = this;
    //如果还有数据就继续加载
    if (!that.data.searchLoading && !that.data.searchLoadingComplete) {
      that.setData({ page: that.data.page + 1 })
      that.setData({
        searchLoading: true   //把"上拉加载"的变量设为false，隐藏

      })
      that.request_indexData(that.data.page)

    }
  },
  //MARK: -- Click
  toDetailsTap: function (e) {
    var id = e.currentTarget.dataset.productid;
    wx.navigateTo({
      url: '../product/productDetail?productId=' + id,
    })
  },
  addCartTap: function (e) {
    if (app.isNeedLogin()) {
      this.getUserInfo()
      return
    };
    this.postAddToCart(e)
  },
  getUserInfo() {
    var that = this
    //调用应用实例的方法获取全局数据
    app.login({
      //success回调
      success: function (endUser) {
        //更新数据
      },
      fail: null,
      authFail: () => { },
    })
  },
  // 添加商品到购物车
  postAddToCart: function (e) {
    var productId = e.currentTarget.dataset.productid;
    var params = {
      productId: productId,
      productQty: 1,
    }

      requests.post_addToCart(params, (res) => {
      if (res.resCode == 0) {
        this.wetoast.toast({
          title: '加入购物车成功',
        })

      } else {
        this.wetoast.toast({
          title: '加入购物车失败',
        })
      }
    }, (res) => {

    }, {})
  },
  //浮动球点击 侧栏展开
  ballClickEvent: function () {
    this.slideUp.call(this);
  },
  //遮罩点击  侧栏关闭
  slideCloseEvent: function () {
    this.slideDown.call(this);
  },

  //banner点击事件
  bannerClick: function (event) {
    var index = event.target.dataset.index;
    this.banner_link(this.data.moduleData[parseInt(index)])

  },

  //MARK: -- private method
  //领券
  get_coupon: function (e) {
    var index = e.target.dataset.index;

    this.request_postCoupons(parseInt(index))


  },


  //全部领取
  get_all_coupon: function (e) {
    if (!this.data.allSelect) {

      var ids = []
      var list = this.data.couponArray;
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        if (!curItem.hasReceived) {
          ids.push(curItem.id)
        }
      }
      this.request_allCoupons(ids)
    }

  },
  /**
 * 判断是否可以全部领取
 */
  allSelect: function () {
    var list = this.data.couponArray;
    var allSelect = false;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.hasReceived) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    this.setData({
      allSelect: allSelect
    })
  },

  banner_link: function (e) {
    var link_type = e.moduleContent.bannerLinkType;

    var link_id = e.moduleContent.bannerLinkTargetId;
    switch (link_type) {
      case 6:   //商品详情页
        wx.navigateTo({
          url: '../product/productDetail?productId=' + link_id,
        })
        break;
      case 8:   //专题详情
        wx.navigateTo({
          url: '../topic/productGroup?topicId=' + link_id,
        })
        break;
      default:
        break;
    }
  },
  //侧栏展开
  slideUp: function (e) {
    if (app.isNeedLogin()) {
      this.getUserInfo()
      return
    };
    this.slideOpen();


  },

  slideOpen: function () {
    this.request_coupons();
    var animation = wx.createAnimation({
      duration: 400
    });
    this.setData({ maskDisplay: 'block' });
    animation.translateY('-100%').step();
    this.setData({
      slideAnimation: animation.export()
    });
  },

  //侧栏关闭
  slideDown: function (e) {
    var animation = wx.createAnimation({
      duration: 400
    });
    animation.translateY('100%').step();
    this.setData({
      slideAnimation: animation.export()

    });
    this.setData({ maskDisplay: 'none' });

  },

  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    return {
      title: '尖叫设计精选商品 | 生活即风格',
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  searchClickEvent:function(){
    wx.navigateTo({
      url: '../search/search',
    })
  }
})



